#include "widget_funcd_weather.h"
#include "ui_widget_funcd_weather.h"
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QStringListModel>
#include <QDate>
widget_funcd_weather::widget_funcd_weather(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::widget_funcd_weather),
    m_networkManager(new QNetworkAccessManager(this)),
    m_networkTimeoutTimer(new QTimer(this)),
    m_cityCompleter(new QCompleter(this))
{
    ui->setupUi(this);
    
    // 初始化城市代码映射
    initCityCodeMap();
    
    // 设置默认城市为长沙
//    ui->cityCodeEdit->setText("长沙");
    
    // 设置自动完成
    m_cityCompleter->setModel(new QStringListModel(m_cityCodeMap.keys(), m_cityCompleter));
    m_cityCompleter->setCaseSensitivity(Qt::CaseInsensitive);
    ui->cityCodeEdit->setCompleter(m_cityCompleter);
    
    // 设置网络超时定时器
    m_networkTimeoutTimer->setSingleShot(true);
    connect(m_networkTimeoutTimer, &QTimer::timeout, this, &widget_funcd_weather::onNetworkTimeout);
    
    // 连接网络请求完成信号
    connect(m_networkManager, &QNetworkAccessManager::finished, this, &widget_funcd_weather::onReplied);
    
    // 设置温度曲线样式
    ui->temperature_label->setHighCurveColor(QColor(255, 100, 0));
    ui->temperature_label->setLowCurveColor(QColor(0, 100, 255));
    ui->temperature_label->setCurveWidth(3);
    ui->temperature_label->setPointSize(10);
    
    QTimer::singleShot(100, this, &widget_funcd_weather::on_searchButton_clicked);
}

widget_funcd_weather::~widget_funcd_weather()
{
    delete ui;
    delete m_networkManager;
    delete m_networkTimeoutTimer;
    delete m_cityCompleter;
}

void widget_funcd_weather::initCityCodeMap()
{
    // 这里可以添加更多城市代码
    m_cityCodeMap.insert("北京", "101010100");
    m_cityCodeMap.insert("上海", "101020100");
    m_cityCodeMap.insert("广州", "101280101");
    m_cityCodeMap.insert("深圳", "101280601");
    m_cityCodeMap.insert("杭州", "101210101");
    m_cityCodeMap.insert("南京", "101190101");
    m_cityCodeMap.insert("成都", "101270101");
    m_cityCodeMap.insert("武汉", "101200101");
    m_cityCodeMap.insert("西安", "101110101");
    m_cityCodeMap.insert("长沙", "101250101");
    m_cityCodeMap.insert("重庆", "101040100");
    m_cityCodeMap.insert("天津", "101030100");
    m_cityCodeMap.insert("厦门", "101230201");
    m_cityCodeMap.insert("海口", "101310101");
    m_cityCodeMap.insert("石家庄", "101090101");
    
}

void widget_funcd_weather::on_searchButton_clicked()
{
    QString input = ui->cityCodeEdit->text().trimmed();
    
    if (input.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入城市名称");
        return;
    }
    
    QString cityCode = input;
    if (m_cityCodeMap.contains(input)) {
        cityCode = m_cityCodeMap.value(input);
    } else if (!input.startsWith("101") || input.length() != 9) {
        QMessageBox::warning(this, "错误", "无效的城市名称或代码");
        return;
    }
    
    // 发起网络请求
    QUrl url("http://t.weather.itboy.net/api/weather/city/" + cityCode);
    m_networkManager->get(QNetworkRequest(url));
    
    // 启动超时计时器(10秒)
    m_networkTimeoutTimer->start(10000);
    
    // 更新UI状态
    ui->searchButton->setEnabled(false);
}

void widget_funcd_weather::onReplied(QNetworkReply *reply)
{
    // 停止超时计时器
    m_networkTimeoutTimer->stop();
    
    // 恢复按钮状态
    ui->searchButton->setEnabled(true);
    ui->searchButton->setText("");
    
    // 检查错误
    if (reply->error() != QNetworkReply::NoError) {
        QMessageBox::warning(this, "错误", reply->errorString());
        reply->deleteLater();
        return;
    }
    
    // 读取并解析数据
    QByteArray data = reply->readAll();
    reply->deleteLater();
    
    if (m_weatherInfo.loadFromJson(QString::fromUtf8(data))) {
        updateCurrentWeatherUI();
        updateForecastUI();
        updateTemperatureCurve();
    } else {
        QMessageBox::warning(this, "错误", "解析天气数据失败");
    }
}

void widget_funcd_weather::onNetworkTimeout()
{
    QMessageBox::warning(this, "超时", "网络请求超时，请检查网络连接");
    ui->searchButton->setEnabled(true);
    ui->searchButton->setText("");
}

void widget_funcd_weather::updateCurrentWeatherUI()
{
    // 更新基本信息
    ui->city->setText(m_weatherInfo.city());
    ui->date_label->setText(m_weatherInfo.date());
    ui->now_temperature->setText(m_weatherInfo.wendu() + "°C");
    ui->humidity_label->setText(m_weatherInfo.shidu());
    ui->air_quality_label->setText(m_weatherInfo.quality());
    
    // 更新今日天气
    if (!m_weatherInfo.forecastList().isEmpty()) {
        const Forecast &today = m_weatherInfo.forecastList().first();
        
        
        QString w_icon = getWeatherIconName(today.type);
        QPixmap icon(QString(":/new/prefix1/%1").arg(w_icon));
        ui->weather_icon->setPixmap(icon.scaled(ui->weather_icon->size(), Qt::KeepAspectRatio ,Qt::SmoothTransformation));
        ui->now_weather_2->setText(today.type);
        
        //温馨提示
        ui->notice_label->setText(today.notice);
        ui->notice_label->setWordWrap(true);  // 启用自动换行
        ui->notice_label->setAlignment(Qt::AlignTop | Qt::AlignLeft);  // 顶部左对齐
    }
    
}

void widget_funcd_weather::updateForecastUI()
{
    QList<Forecast> forecasts = m_weatherInfo.forecastList();
        if (forecasts.size() < 7) return;
        
        // 获取所有UI标签引用
        QList<QLabel*> weekLabels = {
            ui->week_label_0, ui->week_label_1, ui->week_label_2,
            ui->week_label_3, ui->week_label_4, ui->week_label_5, ui->week_label_6
        };
        
        QList<QLabel*> dateLabels = {
            ui->date_label_0, ui->date_label_1, ui->date_label_2,
            ui->date_label_3, ui->date_label_4, ui->date_label_5, ui->date_label_6
        };
        
        QList<QLabel*> iconLabels = {
            ui->icon_label_0, ui->icon_label_1, ui->icon_label_2,
            ui->icon_label_3, ui->icon_label_4, ui->icon_label_5, ui->icon_label_6
        };
        
        QList<QLabel*> degLabels = {
            ui->deg_label_0, ui->deg_label_1, ui->deg_label_2,
            ui->deg_label_3, ui->deg_label_4, ui->deg_label_5, ui->deg_label_6
        };
        
        QList<QLabel*> windLabels = {
            ui->wind_label_0, ui->wind_label_1, ui->wind_label_2,
            ui->wind_label_3, ui->wind_label_4, ui->wind_label_5, ui->wind_label_6
        };
    
        
        // 2. 更新其他6天的信息
        for (int i = 0; i < 7; ++i) {
            const Forecast &forecast = forecasts[i];
            
            // 确保文本居中
            weekLabels[i]->setAlignment(Qt::AlignCenter);
            dateLabels[i]->setAlignment(Qt::AlignCenter);
            degLabels[i]->setAlignment(Qt::AlignCenter);
            windLabels[i]->setAlignment(Qt::AlignCenter);
            
            // 更新内容
            weekLabels[i]->setText(forecast.week);
            
            // 格式化日期 (MM/dd)
            QDate date = QDate::fromString(forecast.ymd, "yyyy-MM-dd");
            dateLabels[i]->setText(date.isValid() ? date.toString("MM/dd") : forecast.ymd.mid(5, 5));
            
            // 更新天气图标
            QString iconName = getWeatherIconName(forecast.type);
            QPixmap icon(QString(":/new/prefix1/%1").arg(iconName));
            iconLabels[i]->setPixmap(icon.scaled(iconLabels[i]->size(), Qt::KeepAspectRatio));
            
            // 1. 设置当天空气质量
            int aqi = forecasts.first().aqi;
            QString aqiText = QString("%1\n%2").arg(aqi).arg(getAqiLevel(aqi));
            
            // 设置样式
            QString styleSheet = QString(
                "QLabel {"
                "   border-radius: 10px;"
                "   padding: 2px;"
                "   qproperty-alignment: 'AlignCenter';"
                "   background-color: %1;"
                "   color: %2;"
                "}"
            ).arg(getAqiColor(aqi),"white");
            
            degLabels[i]->setStyleSheet(styleSheet);
            degLabels[i]->setText(aqiText);
           
            
            // 更新风力（简化为只显示风向）
            windLabels[i]->setText(forecast.fx);
        }
}

void widget_funcd_weather::updateTemperatureCurve()
{
    ui->temperature_label->setWeatherData(m_weatherInfo.forecastList());
}

QString widget_funcd_weather::getWeatherIconName(const QString &weatherType) const
{
    if (weatherType.contains("晴")) return "晴";
    if (weatherType.contains("云")) return "多云";
    if (weatherType.contains("阴")) return "阴";
    if (weatherType.contains("雨")) return "雨";
    if (weatherType.contains("雪")) return "雪";
    if (weatherType.contains("雷")) return "雷阵雨";
    if (weatherType.contains("雾") || weatherType.contains("霾")) return "雾";
    return "未知";
}
